package com.qf.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsCategoryMapper;
import com.qf.pojo.DtsCategory;
import com.qf.service.AdminCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;


@Service
public class AdminCategoryServiceImpl implements AdminCategoryService {

    @Autowired
    private DtsCategoryMapper dtsCategoryMapper;

    @Override
    public IPage<DtsCategory> selectCategoryList(Integer page, Integer limit, Integer id, String name, String sort, String order) {

        IPage<DtsCategory> iPage = new Page<>(page, limit);

        QueryWrapper<DtsCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", false);
        wrapper.eq(id!= null,"id", id);
        wrapper.like(!StringUtils.isEmpty(name), "name", name);
        wrapper.orderByAsc("asc".equalsIgnoreCase(order),sort);
        wrapper.orderByDesc("desc".equalsIgnoreCase(order),sort);

        IPage<DtsCategory> result = dtsCategoryMapper.selectPage(iPage, wrapper);
        return result;
    }

    @Override
    public List<DtsCategory> selectCategoryL1() {

        QueryWrapper<DtsCategory> wrapper = new QueryWrapper<>();
        wrapper.select("id","`name`");
        wrapper.eq("deleted", false);
        wrapper.eq("pid", 0);
        List<DtsCategory> categories = dtsCategoryMapper.selectList(wrapper);
        return categories;
    }

    @Override
    public DtsCategory insertCategory(DtsCategory dtsCategory) {

        if (dtsCategory.getPid() == null){
            dtsCategory.setPid(0);
        }
        dtsCategory.setDeleted(false);
        dtsCategoryMapper.insert(dtsCategory);
        QueryWrapper<DtsCategory> wrapper = new QueryWrapper<>();
        wrapper.select("id");
        wrapper.eq("`name`", dtsCategory.getName());
        wrapper.eq("deleted", false);
        DtsCategory category = dtsCategoryMapper.selectOne(wrapper);
        dtsCategory.setId(category.getId());
        return dtsCategory;
    }

    @Override
    public void updateCategory(DtsCategory dtsCategory) {
        dtsCategory.setUpdateTime(new Date());
        dtsCategoryMapper.updateById(dtsCategory);
    }

    @Override
    public void deleteCategory(Integer id) {
        DtsCategory dtsCategory = new DtsCategory();
        dtsCategory.setId(id);
        dtsCategory.setDeleted(true);
        dtsCategoryMapper.updateById(dtsCategory);
    }
}
